<?php

namespace app\controllers\admin\uni\finance;

use app\award\Profit;
use app\controllers\admin\base\AdminController;
use app\models\order\Order;
use app\models\SetUserUp;
use app\models\user\User;
use app\models\user\UserAccount;
use app\models\user\UserCommission;
use app\models\user\UserCommission as Model;
use app\models\user\UserLevel;
use app\models\Year;

class ProfitController extends AdminController
{
    public function actionList()
    {
        $user_id = $this->post('user_id');
        $export = $this->post('export');

        $month = $this->post('month', date('Y-m-d'));

        $page = intval($this->post('page', $this->page));
        $page_size = intval($this->post('pageSize', $this->pageSize));

        $sort = $this->post('sort');

        $query = Model::find()
            // ->where(['type' => 10])
            ->where(['status' => 10]);

        // $query = (new \yii\db\Query())
        //     ->select('sum(balance) as sum, user_id')
        //     ->from('user_commission')
        //     ->where('status = 10')
        //     ->groupBy(['user_id'])
        //     ->limit(2)
        //     ->all();
        // var_dump($query);exit;

        // if ($sort) {
        //     $prop = substr($sort, 0, 1);
        //     $prop = $prop == '-' ? SORT_DESC : SORT_ASC;
        //     $order = substr($sort, 1);
        //     $query->orderBy([$order => $prop]);
        // } else {
        //     $query->orderBy(['id' => SORT_DESC]);
        // }

        if ($user_id) {
            $query->andWhere(['user_id' => $user_id]);
        }

        if ($month) {
            $query->andWhere(['DATE_FORMAT(create_time, "%Y-%m")' => date('Y-m', strtotime($month))]);
        }

        $query->select('sum(balance) as sum, user_id')
            ->groupBy(['user_id']);

        // export
        if ($export) {
            $e = $query->asArray()->all();
            foreach ($e as &$item) {
                $item['user'] = User::findOne(['id' => $item['user_id']]);
                if ($item['user']['nickname']) {
                    $item['user']['nickname'] = base64_decode($item['user']['nickname']);
                }
                $item['month'] = $month;
            }
            return $this->success($e);
        }

        $totalCount = $query->count();
        $totalPage = ceil($totalCount / $page_size);

        $list = $query->offset(($page - 1) * $page_size)
            ->limit($page_size)
            ->with('user')
            ->asArray()
            ->all();

        foreach ($list as &$item) {
            $item['user'] = User::findOne(['id' => $item['user_id']]);
            if ($item['user']['nickname']) {
                $item['user']['nickname'] = base64_decode($item['user']['nickname']);
            }
            $item['month'] = $month;
        }

        return $this->success([
            $this->totalCount   => $totalCount,
            $this->totalPage    => $totalPage,
            $this->list         => $list,
        ]);

    }

    // 这个是真实需要的分红
    public function actionYear()
    {
        $list = Year::find()
            ->with(['user', 'user.level0', 'user.level2'])
            ->orderBy(['id' => SORT_DESC])
            ->asArray()
            ->all();

        if ($list) {
            foreach ($list as &$item) {
                if ($item['user']['nickname']) {
                    $item['user']['nickname'] = base64_decode($item['user']['nickname']);
                }
            }
        }

        return $this->success(['list' => $list]);
    }

    // 处理分红
    public function actionRunYear()
    {
        $has_day = Year::find()
            ->where(['DATE_FORMAT(create_time, "%Y-%m-%d")' => date('Y-m-d')])
            ->one();
        if ($has_day) {
            return $this->fail('今天已经处理过分红了');
        }

        $transaction = \Yii::$app->db->beginTransaction();
        try {

            // 减肥
            $users = User::find()
                ->where(['level' => [
                    UserLevel::$keys['vip2'],
                    UserLevel::$keys['vip3'],
                ]])
                ->all();
            if ($users) {
                foreach ($users as $user) {
                    $this->_y1($user);
                }
            }

            // 面部
            $list = Profit::getList();
            // var_dump($list);exit;
            foreach ($list as $user) {
                if (!isset($user['real_amount']) || $user['amount'] == 0) {
                    continue;
                }

                $year = new Year();
                $year->user_id = $user['id'];
                $year->level = UserLevel::$keys['vip24'];
                $year->total = $user['total'];
                // 这里改成子团队分红了
                $year->children_total = $user['first_child'];
                $year->amount = $user['real_amount'];
                $year->ratio = $user['ratio'];
                $year->type = 2;
                $year->save();

                $this->saveCommission($user['id'], $year->id, $user['real_amount'], 102, '业绩分红');
            }


            $transaction->commit();
            return $this->success();
        } catch (\Exception $e) {
            $transaction->rollBack();
            var_dump($e->getMessage(), $e->getLine(), $e->getFile());
        }
    }

    private function _y1(User $user)
    {
        $set = SetUserUp::getLastOne();

        // 直推数量
        $children = User::find()
            ->where(['referrer_id' => $user->id])
            ->andWhere(['>=', 'level', UserLevel::$keys['vip1']])
            ->select(['id'])
            ->column();
        if (count($children) < $set->profit1_num) {
            return;
        }

        $ids = array_merge([$user->id], $children);
        // $sum = $this->_total($ids);

        // 这里的业绩只算了自己和直推人的
        $sum = ProfitController::_total($ids, 1);

        if (count($children) >= $set->profit2_num) {
            $ratio = $set->profit2_ratio;
        } else {
            $ratio = $set->profit1_ratio;
        }

        $commission = $sum * $ratio / 100;

        // var_dump($commission);exit;

        // 记录到year表中
        $year = new Year();
        $year->user_id = $user->id;
        $year->level = $user->level;
        $year->total = $sum;
        $year->amount = $commission;
        $year->ratio = $ratio;
        $year->recommend_num = count($children);
        $year->type = 1;
        $year->save();

        $this->saveCommission($user->id, $year->id, $commission, 101, '业绩分红');
    }

    // 总业绩
    public static function _total($ids, $type = 1)
    {
        // 最后一条记录
        $last = Year::find()
            ->orderBy(['id' => SORT_DESC])
            // 类型
            ->andWhere(['type' => $type])
            ->one();
        if ($last) {
            // $last_day = strtotime($last->create_time);
            // $last_day = date('Y-m-d', $last_day);
            $last_day = $last->create_time;
        } else {
            // $last_day = date('Y-m-d');
            $last_day = false;
        }

        $query = Order::find()
            ->where(['user_id' => $ids])
            ->andWhere(['!=', 'status', Order::$statusMapping['NON_PAYMENT']])
            ->andWhere(['!=', 'status', Order::$statusMapping['CANCEL']])
            ->andWhere(['!=', 'status', Order::$statusMapping['DELETE']])
            ->andWhere(['!=', 'status', Order::$statusMapping['REFUND']]);

        // 最后一条记录, 也就是订单开始的时间
        // 计算可能需要几秒, 可以忽略不计
        if ($last_day) {
            $query->andWhere(['>', 'create_time', $last_day]);
        }

        $list = $query->select(['total_pay', 'total_freight'])
            ->asArray()
            ->all();

        $sum = 0;
        foreach ($list as $item) {
            $sum += $item['total_pay'] - $item['total_freight'];
        }

        return $sum;
    }

    // 总佣金(2套)
    public static function _amount($total)
    {
        $set = SetUserUp::getLastOne();

        // 100万以内, 是否给分红
        if ($total < $set->s2_profit_num_1 * 10000) {
            return [0, 0];
        }

        $ratio = 0;
        if ($total >= $set->s2_profit_num_5 * 10000) {
            $ratio = $set->s2_profit_ratio_5;
        }
        else if ($total >= $set->s2_profit_num_4 * 10000) {
            $ratio = $set->s2_profit_ratio_4;
        }
        else if ($total >= $set->s2_profit_num_3 * 10000) {
            $ratio = $set->s2_profit_ratio_3;
        }
        else if ($total >= $set->s2_profit_num_2 * 10000) {
            $ratio = $set->s2_profit_ratio_2;
        }
        else {
            $ratio = $set->s2_profit_ratio_1;
        }

        return [$ratio * $total / 100, $ratio];
    }

    protected function saveCommission($user_id, $order_id, $balance, $type, $name)
    {
        if ($balance >= 0.01) {
            $model = new UserCommission();
            $model->user_id = $user_id;
            $model->fans_id = 0;
            $model->order_id = $order_id;
            $model->balance = $balance;
            // $model->status = $status;
            $model->status = 1;
            $model->award_name = $name;
            $model->award_type = $type;
            $model->save();

            $account = UserAccount::findOne(['user_id' => $user_id]);
            if ($account) {
                $account->balance += $balance;
                // 改成待返
                // $account->await_balance += $balance;
                $account->save();
            }
        }
    }
}